<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in employeesList" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import { addDepartment, getDepartmentId, upDepartment } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验部门编码的唯一性
    const validCode = (rule, value, callback) => {
      console.log(value, 'value')
      console.log(this.originList, 'this.originList')
      let existCodeList = this.originList.map(item => item.code)
      // 编辑状态 先移除自己的编码
      if (this.doEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      console.log(existCodeList, 'existCodeList')
      if (existCodeList.includes(value)) {
        // 存在，抛出错误，提示用户该编码已存在
        callback(new Error(`部门编码: ${value} 已存在 `))
      } else {
        callback() // 放行
      }
    }
    // 校验部门名称的唯一性
    const validName = (rule, value, callback) => {
      console.log(value, 'value')
      console.log(this.id, 'this.id')
      console.log(this.originList, 'this.originList')
      // this.id就是父级的id 新增子部门的pid
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      if (this.isEdit) {
        // 在所有部门中找到当前编辑的部门数据对象
        const cuDepartment = this.originList.find(item => item.id === this.id)
        // 找到当前编辑的部门的pid
        const pid = cuDepartment.pid
        // 所有的兄弟部门的pid是一样的 找到所有的兄弟 包括自己
        const brothers = this.originList.filter(item => item.pid === pid)
        // 排除自己
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      console.log(existNameList, 'existNameList')
      if (existNameList.includes(value)) {
        // 存在，抛出错误，提示用户该编码已存在
        callback(new Error(`部门名称: ${value} 已存在 `))
      } else {
        callback() // 放行
      }
    }
    return {
      // 收集表单信息
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }],
        manager: [{ required: true, message: '请输入部门负责人', trigger: 'blur' }],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入长度是1~300的字符', trigger: 'blur' }
        ]
      },
      employeesList: [] // 负责人列表
    }
  },
  // 解决数据不更新的方式3，使用watch侦听id的变化
  // watch: {
  // 'id': function(newVal, oldVal) {
  //   console.log(newVal, oldVal)
  //   this.loadDepartsDetail()
  // }
  // 深度监听
  //   'id': {
  //     handler: function(newVal, oldVal) {
  //       this.loadDepartsDetail()
  //     },
  //     deep: true, // 开启深度
  //     immediate: true // 组件一加载，就执行
  //   }
  // },
  // 页面刷新时执行
  created() {
    this.loadDepartmentSimple()
    if (this.isEdit) {
      this.loadDepartsDetail()
    }
  },
  methods: {
    // 获取当前部门信息
    async loadDepartsDetail() {
      const res = await getDepartmentId(this.id)
      console.log(res, 'getDepartmentId')
      this.form = res.data
    },
    // 获取下拉框部门负责人
    async loadDepartmentSimple() {
      // 获取部门负责人
      try {
        const res = await getEmployeesSimple()
        console.log(res, 'getEmployeesSimple')
        if (res.code === 10000) {
          this.employeesList = res.data
        }
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      }
    },
    // 绑定提交事件
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
      })
      // 实现新增子部门
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    // 新增子部门
    async doAdd() {
      try {
        const res = await addDepartment({ ...this.form, pid: this.id })
        console.log(res, 'addDepartment')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新渲染列表 关闭弹层
        // 子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      }
    },
    // 编辑部门
    async doEdit() {
      const res = await upDepartment(this.form)
      console.log(res, 'upDepartment')
      if (res.code !== 10000) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 重新渲染列表 关闭弹层
      // 子传父
      this.$emit('success')
    },
    // 重置表单的校验规则和数据
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>
